package cn.xw.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-17 17:10
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    //直接延迟交换机名称
    public static final String DELAYED_EXCHANGE = "delayedExchange";
    //延迟队列名称（但不是在队列中延迟）
    public static final String DELAYED_QUEUE = "delayedQueue";
    //绑定路由key
    public static final String DELAYED_ROUTING_KEY = "delayedRoutingKey";

    /***
     * 创建交换机消息
     * @return Exchange
     */
    @Bean("delayedExchange")
    public CustomExchange delayedExchange() {
        //因为通过ExchangeBuilder没有那个延迟交换机的类型，所以我们使用其它交换机
        //其它参数
        Map<String, Object> args = new HashMap<>();
        //自定义交换机的类型；（虽然设置的是延迟交换机，但是具体四大类型还是得有）
        args.put("x-delayed-type", "direct");
        //参数：交换机名称、交换机类型、是否持久化交换机、是否断开自动删除、其它参数
        return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", true, false, args);
    }

    /***
     * 队列名称
     * @return Queue
     */
    @Bean("delayedQueue")
    public Queue delayedQueue() {
        return QueueBuilder.durable(DELAYED_QUEUE).build();
    }

    /***
     * 绑定关系
     * @param delayedExchange 交换机消息
     * @param delayedQueue 队列消息
     * @return Binding
     */
    @Bean("delayedQueueBindDelayedExchange")
    public Binding delayedQueueBindDelayedExchange(@Qualifier(value = "delayedExchange") CustomExchange delayedExchange,
                                                   @Qualifier(value = "delayedQueue") Queue delayedQueue) {
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }
}
